
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
// navinfo
const navModel = require("../models/nav_list")
const navinfo = navModel(sequelize);
const navLikeModel = require("../models/nav_list_like")
const navinfoLike = navLikeModel(sequelize);

const fileModel = require("../models/file")
const fileinfo = fileModel(sequelize);

const userModel = require("../models/email_user")
const userinfo = userModel(sequelize);

const navTypeModel = require("../models/nav_type")
const navTypeinfo = navTypeModel(sequelize);

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const fs = require('fs');
const path = require('path');

// 根据类型返回列表
router.get('/adminlist', async (ctx) => {
    try {
        let where = {}

        let userid = await getUserID(ctx);
        // 有正确的token
        if (userid) {
            where = { userid: userid }
        }
        // 有token token是错误的
        if (userid == '-1') {
            ctx.body = util.resultSuccess({ code: -1, message: '登录过期，请重新登录', data: null });
            return
        }
        let reqQuery = ctx.request.query;
        where['ntitle'] = {
            [Op.like]: '%' + (reqQuery.keyword ? reqQuery.keyword : '') + '%'
        }
        where['typeid'] = {
            [Op.like]: '%' + (reqQuery.typeid ? reqQuery.typeid : '') + '%'
        }

        navinfo.belongsTo(navTypeinfo, { foreignKey: 'typeid' });
        let navData = await navinfo.findAndCountAll(
            {
                attributes: {
                    // exclude: ['typeid', 'orderid', 'deletedAt', 'updatedAt'],
                },
                include: [
                    {
                        attributes: {
                            exclude: ['deletedAt', 'typeid'],
                        },
                        model: navTypeinfo,
                    }
                ],
                where: where,
                order: [  //排序 DESC ASC
                    // ['orderid', 'ASC']
                ],
                limit: reqQuery.pageSize ? parseInt(reqQuery.pageSize) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0
            }
        );
        ctx.body = util.resultSuccess({ data: navData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})

// 根据类型返回列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let where = { userid: '0' },
            include = [],
            include1 = [],
            whereList = {}

        let userid = await getUserID(ctx);
        let switchType = Cookie('switchType', ctx.request.header.cookie)
        // console.log('switchType1==>',ctx.request.header)
        switchType = reqQuery.switchType ? reqQuery.switchType : switchType
        // console.log('switchType2==>',switchType)
        // console.log('switchType==>',userid)
        
        // 有token token是错误的
        if (userid == '-1') {
            ctx.body = util.resultSuccess({ code: -1, message: '登录过期，请重新登录', data: null });
            return
        }
        navTypeinfo.hasMany(navinfo, { foreignKey: 'typeid', targetKey: 'typeid' });
        include = [{
            order: [  //排序 createdAt ASC
                ['createdAt', 'ASC']
            ],
            // where: whereList,
            attributes: {
                exclude: ['deletedAt', 'userid'],
            },
            model: navinfo,
        }]
       
        // 有正确的token
        if (userid && switchType == 'my') {
            where = {
                userid: userid
            }
            whereList = {}
        } else
            if (userid && switchType == 'all') {
                // 这里会查收藏
                navinfo.hasMany(navinfoLike, { foreignKey: 'oldId', targetKey: 'id' });
                where = { userid: '0' }
                include[0]['include'] = [{
                    required: false,
                    where: { userid: userid },
                    model: navinfoLike,
                    attributes: [['ntitle', 'islike']],
                }]
            }


        console.log('where', where)
        // 查正常表
        let navData = await navTypeinfo.findAll(
            {
                attributes: {
                    exclude: ['sort', 'deletedAt', 'updatedAt'],
                },
                where: where,
                order: [  //排序 DESC ASC
                    ['sort', 'ASC']
                ],
                include: include,
            }
        );


        // 有正确的token
        if (userid && switchType == 'my') {
            navTypeinfo.hasMany(navinfoLike, { foreignKey: 'typeid', targetKey: 'typeid' });
            // 查关注表
            let navData1 = await navTypeinfo.findAll(
                {
                    attributes: {
                        exclude: ['sort', 'deletedAt', 'updatedAt'],
                    },
                    order: [  //排序 DESC ASC
                        ['sort', 'ASC']
                    ],
                    include: [
                        {
                            order: [
                                ['createdAt', 'ASC']
                            ],
                            where: {
                                userid: userid
                            },
                            attributes: {
                                exclude: ['deletedAt', 'userid'],
                            },
                            model: navinfoLike,
                        }
                    ],
                }
            );
            if (navData1.length > 0) {
                navData = navData.concat(navData1)
            }
            let newListKey = []
            let newList = []
            // 重新组合
            navData.forEach(element => {
                let index = newListKey.indexOf(element.typename)
                if (index != -1) {
                    element.lists.map(item => {
                        newList[index].lists.push(item)
                    })
                } else {
                    newListKey.push(element.typename)
                    newList.push(element)
                }
            });
            // console.log('-=====>')
            // console.log('-=====>', newList[1].lists.length)
            // console.log('-=====>')
            ctx.body = util.resultSuccess({ data: newList });
            return
        }

        ctx.body = util.resultSuccess({ data: navData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})

// 查询类型列表
router.get('/typelist', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let cardData = await navTypeinfo.findAll(
            {
                attributes: {   // exclude排除
                    exclude: ['id', 'deletedAt'],
                },
                limit: reqQuery.pageSize ? parseInt(reqQuery.pageSize) : 99,
                offset: reqQuery.page ? parseInt(reqQuery.page) : 0
            }
        );
        ctx.body = util.resultSuccess({ data: cardData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})



/**
 * 修改
 * */
router.post('/editById', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("ntitle")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("nurl")
            .required("地址不能为空")
            .isString()
            .trim()
        let reqBody = ctx.request.body;
        // navinfoLike
        let queryData = {
            ntitle: reqBody.ntitle ? reqBody.ntitle : '',
            ndetail: reqBody.ndetail ? reqBody.ndetail : '',
            typeid: reqBody.typeid ? reqBody.typeid : '',
            nurl: reqBody.nurl ? reqBody.nurl : '',
            fileId: reqBody.fileId ? reqBody.fileId : '',
            // isopen: reqBody.isopen ? reqBody.isopen : 0,
        }
        let requestData = null
        console.log('reqBody.isopen==>', reqBody)
        // return
        if (reqBody.isopen == 2 || reqBody.isopen == 3) {
            requestData = await navinfoLike.update(queryData, {
                where: {
                    id: reqBody.id
                }
            })
        } else {
            requestData = await navinfo.update(queryData, {
                where: {
                    id: reqBody.id
                }
            })
        }

        if (requestData[0] > 0) {
            ctx.body = util.resultSuccess({ message: '修改成功', data: null });
        } else {
            ctx.body = util.resultError({ code: 0, message: '修改失败,id错误', data: null });
        }

    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

/**
 * 新增
 * */
router.post('/add', async (ctx) => {
    try {
        ctx
            .validateBody("ntitle")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("nurl")
            .required("地址不能为空")
            .isString()
            .trim()

        let userid = await getUserID(ctx);

        let reqBody = ctx.request.body;
        console.log('reqBody=>', reqBody)
        let requestData = await navinfo.create({
            id: getuuid(),
            ntitle: reqBody.ntitle ? reqBody.ntitle : '',
            ndetail: reqBody.ndetail ? reqBody.ndetail : '',
            typeid: reqBody.typeid ? reqBody.typeid : '',
            nurl: reqBody.nurl ? reqBody.nurl : '',
            nimg: reqBody.nimg ? reqBody.nimg : '',
            isopen: reqBody.isopen ? reqBody.isopen : 0,
            fileId: reqBody.fileId ? reqBody.fileId : 0,
            userid: userid
        })
        if (requestData.dataValues) {
            ctx.body = util.resultSuccess({ message: '添加成功', data: requestData.dataValues });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '添加失败', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
/**
 * 新增
 * */
router.post('/addA', async (ctx) => {
    try {
        let userid = await getUserID(ctx);

        let reqBody = ctx.request.body;
        // console.log('reqBody=>', reqBody)

        // id: getuuid(),
        // ntitle: reqBody.ntitle ? reqBody.ntitle : '',
        // ndetail: reqBody.ndetail ? reqBody.ndetail : '',
        // typeid: reqBody.typeid ? reqBody.typeid : '',
        // nurl: reqBody.nurl ? reqBody.nurl : '',
        // nimg: reqBody.nimg ? reqBody.nimg : '',
        // isopen: reqBody.isopen ? reqBody.isopen : 0,
        // fileId: reqBody.fileId ? reqBody.fileId : 0,
        // userid: userid
        let fileDatas = []
        const dir = path.join(__dirname, `../public/upload/import/`);
        let list = reqBody.list.map(item => {
            // 随机文件名
            var fileName = ''
            if (item.icon) {
                fileName = getuuid();
                var base64Data = item.icon.replace(/^data:image\/\w+;base64,/, "");
                var dataBuffer = new Buffer(base64Data, 'base64');
                fs.writeFile(dir + fileName + '.png', dataBuffer, function (err) {
                    if (err) {
                        console.log("fff", err)
                    } else {
                        console.log("fff")
                    }
                })
            }
            fileDatas.push({
                filename: 'import/' + fileName + '.png',
                fileid: fileName
            });
            return {
                fileId: fileName,
                ntitle: item.title,
                ndetail: item.title,
                id: getuuid(),
                nurl: item.url,
                userid: userid,
                typeid: 'import',
                isopen: 3,
            }
        })

        var requestDataIcon = await fileinfo.bulkCreate(fileDatas)
        let requestData = await navinfoLike.bulkCreate(list)
        if (requestData.length == list.length) {
            ctx.body = util.resultSuccess({ message: '导入成功', data: requestData.dataValues });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '导入失败', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
/**
 * 收藏
 * */
router.post('/like', async (ctx) => {
    try {
        ctx
            .validateBody("ntitle")
            .required("收藏失败")
            .isString()
            .trim()
        ctx
            .validateBody("nurl")
            .required("收藏失败")
            .isString()
            .trim()

        let userid = await getUserID(ctx);
        let reqBody = ctx.request.body;
        // 判断是否存在了
        let requestData1 = await navinfoLike.findOne({
            where: {
                userid: userid,
                oldId: reqBody.id
            }
        })
        if (requestData1) {
            ctx.body = util.resultSuccess({ code: 0, message: '已经收藏啦', data: null });
            return
        }

        let requestData = await navinfoLike.create({
            id: getuuid(),
            ntitle: reqBody.ntitle ? reqBody.ntitle : '',
            ndetail: reqBody.ndetail ? reqBody.ndetail : '',
            typeid: 'like',
            nurl: reqBody.nurl ? reqBody.nurl : '',
            nimg: reqBody.nimg ? reqBody.nimg : '',
            isopen: 2,
            fileId: reqBody.fileId ? reqBody.fileId : '',
            userid: userid,
            oldId: reqBody.id
        })
        if (requestData.dataValues) {
            ctx.body = util.resultSuccess({ message: '收藏成功', data: requestData.dataValues });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '收藏失败', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
/**
 * 删除
 * */
router.post('/delById', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()
        let requestData = null
        let reqBody = ctx.request.body;


        if (reqBody.isopen == 2) {
            requestData = await navinfoLike.destroy({
                where: {
                    id: ctx.vals.id
                }
            })
        } else {
            requestData = await navinfo.destroy({
                where: {
                    id: ctx.vals.id
                }
            })
        }

        if (requestData > 0) {
            ctx.body = util.resultSuccess({ message: '删除成功' });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '删除失败', data: requestData });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
function getuuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    var uuid = s.join("");
    return uuid;
}
function Cookie(name, cookies) {
    var CookieValue = null;
    if (cookies) {
        var Cookies = cookies.split(";");
        for (var i = 0; i < Cookies.length; i++) {
            var Cookie = (Cookies[i] || "").replace(/^\s+|\s+$/g, "");
            //这个if写的屌
            if (Cookie.substring(0, name.length + 1) == (name + '=')) {
                CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return CookieValue;
}

async function getUserID(ctx) {
    // console.log('cookie--->>', ctx.request.header)
    let token = Cookie('token', ctx.request.header.cookie)
    token = token ? token : ctx.request.header.authorization

    if (!token) {
        return ''
    }
    let userData = await userinfo.findOne(
        {
            where: {
                token: token
            },
        }
    );
    console.log('userData', userData);
    if (userData) {
        return userData._id
    } else {

        return '-1'
    }
}
module.exports = router.routes();